package org.devops

//获取在Pom文件中获取坐标
def GetGav(){
	// 上传制品前获取制品信息
	def jarName =  sh returnStdout: true, script: "cd target;ls *.jar"  //获取jar包名称
	env.jarName = "${jarName}" - "\n"

	def pom = readMavenPom file: 'pom.xml'   //读入pom.xml文件并获取信息
	env.pomVersion = "${pom.version}"
	env.pomArtifact = "${pom.artifactId}"
	env.pomPackaging = "${pom.packaging}"
	env.pomGroupId = "${pom.groupId}"

	println("${pomGroupId}-${pomArtifact}-${pomVersion}-${pomPackaging}")

	return ["${pomGroupId}","${pomArtifact}","${pomVersion}","${pomPackaging}"]
}


//使用Nexus插件上传制品
	def NexusUpload(){
	nexusArtifactUploader artifacts: [[artifactId: "${pomArtifact}",  // 获取包的信息
										classifier: '',
										file: "${filePath}",
										type: "${pomPackaging}"]],
							credentialsId: 'nexus-admin-user',  //认证信息
							groupId: "${pomGroupId}",          // 仓库信息
							nexusUrl: '192.168.70.33:8081', 
							nexusVersion: 'nexus3', 
							protocol: 'http', 
							repository: "${repoName}", 
							version: "${pomVersion}"
}


//使用maven上传制品
def MavenUpload(){
	def mvnHome = tool "m2"    //指定maven
	sh """
		cd target/
		${mvnHome}/bin/mvn deploy:deploy-file \
		-Dmaven.test.skip=true \
		-Dfile=${jarName} \
		-DgroupId=${pomGroupId} \
		-DartifactId=${pomArtifact} \
		-Dversion=${pomVersion} \
		-Dpackaging=${pomPackaging} \
		-DrepositoryId=maven-hostd \
		-Durl=http://192.168.70.33:8081/repository/maven-hostd
	"""
}

// 制品晋级
def ArtifactUpdate(updateType,artifactUrl){
	//晋级策略
	if ("${updateType}" == "snapshot -> release") {
		println("snapshot -> release")

		//下载原始制品
		sh "rm -fr updates && mkdir updates && cd updates && wget ${artifactUrl} && ls -l"

		//获取articleID
		//com/mycompany/app/my-app/1.1-SNAPSHOT/my-app-1.1-20200620.115226-3.jar
		artifactUrl = artifactUrl - "http://192.168.70.33:8081/repository/maven-hostd/"
		artifactUrl = artifactUrl.split("/").toList()

		println(artifactUrl.size())
		env.jarName = artifactUrl[-1]
		env.pomVersion = artifactUrl[-2].replace("SNAPSHOT","RELEASE")
		env.pomArtifact = artifactUrl[-3]
		env.pomPackaging = artifactUrl[-1]
		pomPackaging = pomPackaging.split("\\.").toList()[-1]
		println(pomPackaging)
		env.pomPackaging = pomPackaging[-1]
		env.pomGroupId = artifactUrl[0..-4].join(".")
		println("${pomGroupId}##${pomArtifact}##${pomVersion}##${pomPackaging}")
		env.newJarName = "${pomArtifact}-${pomVersion}.${pomPackaging}"

		//更改名称
		sh "cd updates && mv ${jarName} ${newJarName}"

		//上传制品
		env.repoName = "maven-releases"
		env.filePath = "updates/${newJarName}"
		NexusUpload()
	}
}



//入口函数
def main(uploadType){
	// 调用获取坐标函数
	GetGav()

	if ("${uploadType}" == "maven") {
		MavenUpload()		
	} else if ("${uploadType}" == "nexus") {
		env.repoName = "maven-hostd"    //定义仓库名
		env.filePath = "target/${jarName}"     //文件名路径
		NexusUpload()
	}
}